package org.comidas;

import java.util.ArrayList;

import org.database.Constants;
import org.database.MyDB;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class ComidasActivity extends ListActivity implements
		OnItemClickListener, OnLongClickListener {

	private ListaComidas comidas;
	private MyDB bd;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		bd = new MyDB(this);
		bd.open();
		comidas = ListaComidas.getInstance();
		comidas.iniciaListaVazia();
		
		for(Comida c : comidasBD()){
			if(c != null){
				comidas.addComida(c);	
			}
		}
	}
	
	private String formataTempoBD(int[] tempo){
		return String.valueOf(tempo[0]) + ' ' + String.valueOf(tempo[1]) + ' ' + String.valueOf(tempo[2]);
	}
	
	private int[] formataTempoLista(String tempo){
		String[] parteDoTempo = tempo.split(" ");
		int[] retornoTempo = new int[3];
		retornoTempo[0] = Integer.valueOf(parteDoTempo[0]);
		retornoTempo[1] = Integer.valueOf(parteDoTempo[1]);
		retornoTempo[2] = Integer.valueOf(parteDoTempo[2]);
		return retornoTempo;
	}
	
	@Override
	protected void onDestroy(){
		super.onDestroy();
		bd.deleteBD();
		for(int i=0; i<comidas.size(); i++){
			bd.insertAlimento(comidas.getComida(i).getNome(), comidas.getComida(i).getDescricao(), formataTempoBD(comidas.getComida(i).getTempo()), comidas.getComida(i).getFoto());
		}
		bd.close();
	}
	
	private ArrayList<Comida> comidasBD() {
		
		Cursor cursor = bd.getAlimentos();
		startManagingCursor(cursor);
		ArrayList<Comida> arrayList = new ArrayList<Comida>();
		if(cursor.moveToFirst()){
			do{
				String nome = cursor.getString(cursor.getColumnIndex(Constants.TITLE_NAME));
				String descricao = cursor.getString(cursor.getColumnIndex(Constants.CONTENT_NAME));
				String tempo = cursor.getString(cursor.getColumnIndex(Constants.TIME_NAME));
				String foto = cursor.getString(cursor.getColumnIndex(Constants.FOTO_NAME));
				
				arrayList.add(new Comida(nome, formataTempoLista(tempo), descricao, foto));
			}while(cursor.moveToNext());
		}
		return arrayList;
	}
	
	public void onResume() {
		super.onResume();

		setListAdapter(new ArrayAdapter<String>(this, R.layout.listacomidas,
				comidas.toArrayString()));

		ListView lv = getListView();
		lv.setTextFilterEnabled(true);

		lv.setOnItemClickListener(this);

		lv.setOnItemLongClickListener(new OnItemLongClickListener() {
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				ListView opcoes = getListView();
				openVisaoDialog(position);
				opcoes.showContextMenu();
				if (opcoes.hasTextFilter()) {
					position = getPositionByName((String) opcoes.getItemAtPosition(position));
				} 
				Toast.makeText(getApplicationContext(), comidas.getComida(position).getNome(),
						Toast.LENGTH_SHORT).show();
				
				return true;

			}
		});

	}

	private void openVisaoDialog(final int position) {
		new AlertDialog.Builder(this)
				.setTitle(R.string.opcoes)
				.setItems(R.array.opcoes,
						new DialogInterface.OnClickListener() {
							public void onClick(
									DialogInterface dialoginterface, int i) {
								menuOpcoes(i, position);
							}
						}).show();

	}

	private void menuOpcoes(int i, int position) {
		if (i == 0) {
			Intent editarIntent = new Intent(this, EditarComida.class);
			if (this.getListView().hasTextFilter()) {
				position = getPositionByName((String) this.getListView().getItemAtPosition(position));
			} 
			editarIntent.putExtra("comida", comidas.getComida(position));
			startActivity(editarIntent);
			this.getListView().clearTextFilter();
		} else if (i == 1) {
			if (this.getListView().hasTextFilter()) {
				position = getPositionByName((String) this.getListView().getItemAtPosition(position));
			} 
			comidas.removeComida(position);
			onResume();
			this.getListView().clearTextFilter();

		}
	}

	private int getPositionByName(String itemAtPosition) {
		int result = 0;
		while (!comidas.getComida(result).getNome().equals(itemAtPosition)){
			result++;
		}
		
		return result;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Log.v(null, "XB");

		switch (item.getItemId()) {
		case R.id.adicionarComida:
			Log.v(null, "vai iniciar");

			Intent addComidaIntent = new Intent(this, AdicionarComida.class);
			startActivity(addComidaIntent);
			Log.v(null, "INICIIIIIIIIIIIIIA");
			return true;
		}
		return false;
	}

	public boolean onLongClick(View v) {

		return false;
	}

	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Intent visualizarIntent = new Intent(this, VisualizarAlimento.class);
		if (this.getListView().hasTextFilter()) {
			position = getPositionByName((String) this.getListView().getItemAtPosition(position));
		} 
		visualizarIntent.putExtra("comida", comidas.getComida(position));
		startActivity(visualizarIntent);
		this.getListView().clearTextFilter();
	}
}
